import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTokenTimeStamp } from '@/utils/auth'
import router from '@/router'
const TimeOut = 3600

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (checkToken()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token超时，请重新登录'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  const { success, message, data } = response.data
  if (success) {
    // console.log(success)
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
  Message.error(error.message)
  return Promise.reject(error)
})

// 检查Token是否过期
const checkToken = () => {
  const curTime = Date.now()
  const TokenStamp = +getTokenTimeStamp() // 注意加+号转为数字形
  return (curTime - TokenStamp) / 1000 > TimeOut
}

export default service
